package com.bear.fastrepair.mvvm.ui.employee

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bear.fastrepair.base.BaseDialog
import com.bear.fastrepair.base.BaseViewHolder
import com.bear.fastrepair.databinding.DialogSelectBinding
import com.bear.fastrepair.databinding.ItemImageUploadBinding
import com.bear.fastrepair.databinding.ItemUploadImageBinding
import com.bear.fastrepair.entity.BitmapInfo
import com.bear.fastrepair.mvvm.ui.employee.dialog.ImageDialog
import com.bear.fastrepair.mvvm.ui.employee.fragment.OrderDetailFragment
import com.blankj.utilcode.util.*
import com.bumptech.glide.Glide
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import java.io.File

class UploadImageDialog(
    context: Context,
    private val list: ArrayList<BitmapInfo>,
    viewModel: EmployeeViewModel,
    private val fragment: OrderDetailFragment,
    private val block: (String, List<File>) -> Unit
) : BaseDialog(context) {

    private var imagesListener: ((List<Uri>) -> Unit)? = null
    private var bitmapListener: ((Bitmap) -> Unit)? = null
    private var uploadList = ArrayList<File>()

    init {
        viewModel.selectedImage.observe(fragment) {
            imagesListener?.invoke(it)
        }
        viewModel.captureImage.observe(fragment) {
            bitmapListener?.invoke(it)
        }
    }

    private lateinit var binding: ItemUploadImageBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ItemUploadImageBinding.inflate(LayoutInflater.from(context))
        setContentView(binding.root)
        val adapter = ImageAdapter(list)
        binding.uploadImageRv.layoutManager =
            LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        binding.uploadImageRv.adapter = adapter
        binding.uploadConfirm.setOnClickListener {
            val remarks = binding.edRemarks.text.toString()
            block(remarks, uploadList)
            dismiss()
        }
    }

    class SelectDialog(context: Context): BaseDialog(context) {
        private lateinit var binding: DialogSelectBinding
        var clickCapture: (() -> Unit)? = null
        var clickGallery: (() -> Unit)? = null

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = DialogSelectBinding.inflate(LayoutInflater.from(context))
            setContentView(binding.root)
            binding.capture.setOnClickListener {
                clickCapture?.invoke()
                dismiss()
            }
            binding.gallery.setOnClickListener {
                clickGallery?.invoke()
                dismiss()
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    inner class ImageAdapter(private val list: ArrayList<BitmapInfo>) :
        RecyclerView.Adapter<ImageAdapter.Holder>() {

        init {
            imagesListener = imagesListener@{
//                    val last = list.last()
                list.addAll(0, it.map { uri -> BitmapInfo(uri = uri) })
//                    list.remove(last)
//                    list.addAll(it.map { uri -> BitmapInfo(uri = uri) })
//                    list.add(last)
                uploadList.addAll(it.map { uri -> UriUtils.uri2File(uri) })
                this.notifyDataSetChanged()
            }
            bitmapListener = {
                val file = ImageUtils.save2Album(it, Bitmap.CompressFormat.JPEG)
                list.add(0, BitmapInfo(file))
                file?.let { it1 -> uploadList.add(it1) }
            }
        }

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): Holder {
            return Holder(
                ItemImageUploadBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            )
        }

        override fun onBindViewHolder(holder: Holder, position: Int) {
            holder.bind(list[position], position)
        }

        override fun getItemCount(): Int {
            return list.size
        }

        inner class Holder(private val binding: ItemImageUploadBinding) :
            BaseViewHolder<BitmapInfo>(binding.root) {
            override fun bind(item: BitmapInfo, index: Int) {
                item.let {
                    when {
                        it.file != null -> {
                            Glide.with(context).load(it.file).into(binding.itemImage)
                        }
                        it.resId != null -> {
                            Glide.with(context).load(it.resId).into(binding.itemImage)
                        }
                        it.uri != null -> {
                            Glide.with(context).load(it.uri).into(binding.itemImage)
                        }
                        it.url != null -> {
                            Glide.with(context).load(it.url)
                                .into(binding.itemImage)
                        }
                        else -> Unit
                    }
                }
                if (index == (list.size - 1)) {
                    binding.itemImage.setOnClickListener {
                        val dialog = SelectDialog(context)
                        dialog.clickGallery = {
                            checkAndOpenGallery {
                                openGallery()
                            }
                        }
                        dialog.clickCapture = {
                            checkAndOpenGallery {
                                openCamera()
                            }
                        }
                        dialog.show()
                    }
                } else {
                    binding.itemImage.setOnClickListener {
                        ImageDialog(context, item).show()
                    }
                }
            }

        }

        private fun checkAndOpenGallery(block: () -> Unit) {
            if (!XXPermissions.isGranted(
                    context,
                    Permission.READ_EXTERNAL_STORAGE,
                    Permission.WRITE_EXTERNAL_STORAGE
                )
            ) {
                XXPermissions.with(context).permission(
                    Permission.READ_EXTERNAL_STORAGE,
                    Permission.WRITE_EXTERNAL_STORAGE
                ).request(object : OnPermissionCallback {
                    override fun onGranted(
                        permissions: MutableList<String>?,
                        all: Boolean
                    ) {
                        block()
                    }

                    override fun onDenied(
                        permissions: MutableList<String>?,
                        never: Boolean
                    ) {
                        super.onDenied(permissions, never)
                        ToastUtils.showLong("没有读写手机图片权限，请授予")
                        XXPermissions.startPermissionActivity(context)
                    }
                })
            } else {
                block()
            }
        }

        fun openGallery() {
            val intent = Intent().apply {
                type = "image/*"
                putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                action = Intent.ACTION_GET_CONTENT
                data = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            }
            ActivityUtils.startActivityForResult(fragment, intent, 1001)
        }

        fun openCamera() {
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
            }
            ActivityUtils.startActivityForResult(fragment, intent, 1002)
        }
    }
}